package com.vote.www.controller;

import com.alibaba.fastjson.JSONObject;
import com.vote.www.core.page.Pagination;
import com.vote.www.domain.Czjuserapprove;
import com.vote.www.domain.vo.TUser;
import com.vote.www.service.ApproveService;
import com.vote.www.service.CzjuserapproveService;
import com.vote.www.utils.UrlUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 汤伟杰 on 2017/4/28.
 */
//@Component
@Controller
@RequestMapping("/approve")
public class ApproveController extends BaseController{
    @Autowired
    private ApproveService approveService;
    @Autowired
    private CzjuserapproveService czjuserapproveService;

   private static final Logger log = LoggerFactory.getLogger(ApproveController.class);

    @RequestMapping({"index.do",""})
    public String index(String q,
                        String pageNo,
                        String pageSize,
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) {
        TUser user = (TUser) req.getSession().getAttribute("user");


        if(user==null){
            return "approveIndex";
        }
        return "redirect:/admin/home.do";
    }


    @RequestMapping(value = "logout.do")
    public String logout(HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) {
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        model.addAttribute("msg","退出登陆");
        return "redirect:index.do";
    }
    @RequestMapping(value = "login.do")
    public String login(String username,
                        String password,
                        String vcode,
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) {

        //登录检查：检查验证码
        String session_vcode = String.valueOf(req.getSession().getAttribute("rand"));
        if(StringUtils.isNotBlank(session_vcode)&&!"null".equals(session_vcode.toLowerCase())) {//为空跳过验证码
            if(StringUtils.isNotBlank(vcode)){
                if(!session_vcode.equals(vcode.trim())){
                    model.addAttribute("username", username);
                    model.addAttribute("password", password);
                    model.addAttribute("vcode", vcode);
                    model.addAttribute("msg", "验证码校验失败");
                    return "approveIndex";
                }else{
                    //验证码校验成功
                }
            }else{
                model.addAttribute("username", username);
                model.addAttribute("password", password);
                model.addAttribute("vcode", vcode);
                model.addAttribute("msg", "验证码不能为空");
                return "approveIndex";
            }

        }
        //登录检查：检查用户名和密码
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            if (approveService.checkLogin(username.trim(), password.trim(), req)) {
                return "redirect:index.do";
            } else {
                model.addAttribute("username", username);
                model.addAttribute("password", password);
                model.addAttribute("vcode", vcode);
                model.addAttribute("msg", "用户名或密码出错");
            }

        }else if(StringUtils.isNotBlank(username) || StringUtils.isNotBlank(password)){
            model.addAttribute("username", username);
            model.addAttribute("password", password);
            model.addAttribute("vcode", vcode);
            model.addAttribute("msg", "用户名或密码不能为空");
        }

        return "approveIndex";
    }


    /**
     * 审批列表
     * @param q 查询姓名/别名/手机号
     * @param approveStatus 查询审批状态
     * @param pageNo 页码
     * @param pageSize 页行数
     * @param req
     * @param resp
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    public String list(String q,
                    String approveStatus,
                    String pageNo,
                     String pageSize,
                     HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model) {
        model.addAttribute("msg", req.getParameter("msg"));
        if (StringUtils.isBlank(pageNo))
            pageNo = "1";
        if (StringUtils.isBlank(pageSize))
            pageSize = "20";
        Map<String,Object> param = new HashMap<String,Object>();
        if(StringUtils.isNotBlank(q)){
            param.put("nick",q);
            param.put("fullName",q);
            param.put("telephone",q);
        }
        if(StringUtils.isNotBlank(approveStatus)){
            param.put("approveStatus",approveStatus);
        }
        Pagination pagination = approveService.getList(param, pageNo, pageSize);
        model.addAttribute("pagination", pagination);
        model.addAttribute("q", q);
        model.addAttribute("approveStatus", approveStatus);
//        List<Map<String, Object>> list = approveService.getList(q, pageNo, pageSize);
//        model.addAttribute("list", list);
        return "approveList";

    }
    @RequestMapping("detail.do")
    public String detail(@RequestParam(required = true) String id,
                      String msg,
                      HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) {
        try {
            if(StringUtils.isNotBlank(msg)){
                model.addAttribute("msg",msg);
            }
            approveService.getDetailById(id,model);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "approveDetail";
    }
    @RequestMapping("record.do")
    public String record(@RequestParam(required = true) String id,//userinfoId
                      String msg,
                      HttpServletRequest req, HttpServletResponse resp,
                      ModelMap model) {
        try {
            if(StringUtils.isNotBlank(msg)){
                model.addAttribute("msg",msg);
            }
            List<Czjuserapprove> list = czjuserapproveService.getUserapproveList(id);

            model.addAttribute("list", list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "approveRecord";
    }
    @RequestMapping("successful.do")
    public String successful(@RequestParam(required = true) String id,
                       HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model) throws UnsupportedEncodingException {
        String msg ="";
        try {
            approveService.setApproveStatus(1,id,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "&msg="+ URLEncoder.encode(e.getMessage(), "UTF-8") ;
        }
        return "redirect:detail.do?id="+id+msg;
    }
    @RequestMapping("unsuccessful.do")
    public String unsuccessful(@RequestParam(required = true) String id,
                        HttpServletRequest req, HttpServletResponse resp,
                        ModelMap model) throws UnsupportedEncodingException {
        String msg ="";
        try {
            approveService.setApproveStatus(2, id, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "&msg="+ URLEncoder.encode(e.getMessage(), "UTF-8") ;
        }

        return "redirect:detail.do?id="+id+msg;
    }
    @RequestMapping("approveStatus.do")
    public void approveStatus(@RequestParam(required = true) String userapproveId,
                                @RequestParam(required = true) int approveStatus,
                               HttpServletRequest req, HttpServletResponse resp,
                               ModelMap model) throws IOException {
        Map<String,Object> map = new HashMap<String,Object>();
//        String msg ="";
        try {
             
            approveService.setApproveStatus(approveStatus, userapproveId, req, resp);
       

            map.put("status", 1);
            map.put("msg","审批通过");
            resp.getWriter().append(JSONObject.toJSONString(map));
        } catch (Exception e) {
//            e.printStackTrace();
            System.err.println("java.lang.Exception: "+e.getMessage());
//            log.error("java.lang.Exception: "+e.getMessage());
            map.put("status", 0);
            map.put("msg",e.getMessage());
            resp.getWriter().append(JSONObject.toJSONString(map));
//            msg = "&msg="+ URLEncoder.encode(e.getMessage(), "UTF-8") ;
        }

//        return "redirect:detail.do?id="+id+msg;
    }
    @RequestMapping("autoupdate.do")
    public void autoupdate(@RequestParam(required = true) int id,
                               HttpServletRequest req, HttpServletResponse resp,
                               ModelMap model) throws Exception {
        czjuserapproveService.aotoUpdate(id);
        resp.getOutputStream().println(id+" success");

    }
    @RequestMapping("isuse.do")
    public void isuse(@RequestParam(required = true) int status,
                      @RequestParam(required = true) String id,
                           HttpServletRequest req, HttpServletResponse resp,
                           ModelMap model) throws Exception {
        Map<String,Object> msg = czjuserapproveService.isuse(status,id);
        resp.getWriter().append(JSONObject.toJSONString(msg));
//        return msg;
    }
    
    
    @RequestMapping("updateUrl")
    public void  updateUrl(@RequestParam(required = true) String userapproveId,
    						@RequestParam(required = true) String vodeoUri,
                           HttpServletRequest req, HttpServletResponse resp,
                           ModelMap model) throws Exception {
    	   Map<String,Object> map =new HashMap<String, Object>();
    	try {
    		boolean validate=UrlUtil.isConnection(vodeoUri);
    		if(false==validate){
    			map.put("sta", "视频地址错误");
    		}else{
    		approveService.updateUrl(userapproveId,vodeoUri);   	
    		map.put("sta", "保存视频网络路径成功");
    		}
		} catch (Exception e) {
			e.printStackTrace();
			log.info("error", e);
			map.put("sta", "保存视频网络路径出错");
		}
    	
    	resp.getWriter().append(JSONObject.toJSONString(map));

    }
    
    @RequestMapping("uploadImg")
    public String uploadImg(@RequestParam(required=true) String picPath,
    		@RequestParam(required=true) String userapproveId,
    		@RequestParam(value = "picPathPng", required = true) MultipartFile file,
    		HttpServletRequest req, HttpServletResponse resp,ModelMap model){
    	
    	
    	try {
			String pathRoot = req.getSession().getServletContext()
					.getRealPath("");
			String picName = picPath.replace("/upload/", "").replace(".jpg", "");
			String path = "/uploadPng/" + picName + ".png";// 数据库保存路径
			  File fileDir = new File(pathRoot + "/uploadPng");
			  if (!fileDir.exists()) {
			      fileDir.mkdir();
			  }
			  file.transferTo(new File(pathRoot + path));
			  Czjuserapprove czjuserapprove=new Czjuserapprove();
			  	czjuserapprove.setUserapproveId(userapproveId);
			  	czjuserapprove.setPicPathPng(path);
			  czjuserapproveService.update(czjuserapprove);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			log.error("error", e);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("error", e);
		}
    	
    	return "redirect:detail.do?id="+userapproveId;
    }
    
    
}
 